# Importing Data
UAE <- read_excel("C:\Users\Biniam\Desktop\Documents\Academic\Thesis\Analysis Folder\Excel Files\UAE.xlsx")

# Checking the Imported Data
View(UAE)
head(UAE)
tail(UAE)

# Creating Time Series Data
UAE_ts <- ts(UAE, start=c(2001,1), end=c(2018,11), frequency=12)

# Viewing and Checking the Created Time Series Data
UAE_ts
cycle(UAE_ts)
start(UAE_ts)
end(UAE_ts)
frequency(UAE_ts)
head(UAE_ts)
tail(UAE_ts)
sum(is.na(UAE_ts))
install.packages("forecast")
library(forecast)
UAE_ts <- tsclean(UAE_ts)
summary(UAE_ts)
UAE_ts

# Step – 1 of the Box-Jenkins Methodology (Identification: Plotting the Time Series Data)
plot(UAE_ts)
plot(aggregate(UAE_ts,FUN=mean))

# Decomposing
UAE_ts_decomp <- decompose(UAE_ts)
plot(UAE_ts_decomp)

# Testing for Stationarity
acf(UAE_ts, lag.max=20)
pacf(UAE_ts, lag.max=20)
install.packages("tseries")
library(tseries)
adf.test((UAE_ts), alternative="stationary", k=0)

# To see any seasonal effect
boxplot(UAE_ts~cycle(UAE_ts))

# To remove trend effect
UAE_ts_diff <- diff(UAE_ts)
plot(UAE_ts_diff)

# To remove variance effect
UAE_ts_log <- log(UAE_ts)
plot(UAE_ts_log)

# To remove both (Trend and Variance) effects
UAE_ts_both <- diff(log(UAE_ts))
plot(UAE_ts_both)

# Testing for Stationarity
# install.packages("tseries")
library(tseries)
adf.test(diff(log(UAE_ts)), alternative="stationary",k=0)

# Dealing with ACF and PACF
# install.packages("tseries")
library(tseries)
acf(UAE_ts, lag.max=20)
acf(log(UAE_ts), lag.max=20)
acf(diff(UAE_ts), lag.max=20)
acf(diff(log(UAE_ts)), lag.max=20)
pacf(UAE_ts, lag.max=20)
pacf(log(UAE_ts), lag.max=20)
pacf(diff(UAE_ts), lag.max=20)
pacf(diff(log(UAE_ts)), lag.max=20)

# Step-2 of the Box-Jenkins Methodology (Estimating the appropriate model)
UAE_ts_model <- auto.arima(UAE_ts)
UAE_ts_model
UAE_ts_model <- auto.arima(UAE_ts, ic="aic", trace = TRUE)
UAE_ts_model

# Step-3 of the Box-Jenkins Methodology (Diagnosis Checking)
library(tseries)
plot.ts(UAE_ts_model$resid)
acf(ts(UAE_ts))
acf(UAE_ts_model$residuals, main='ACF Residual')
pacf(UAE_ts_model$residuals, main='ACF Residual')
Box.test(UAE_ts_model$resid, lag=20, type="Ljung-Box")

# Forecasting
options(max.print=1000000)
# install.packages("forecast")
library(forecast)
UAE_ts_forecast <- forecast (UAE_ts_model, level=c(95), h=240)
plot(UAE_ts_forecast)
UAE_ts_forecast
